#!/bin/bash

# 房间满员自动开始比赛功能测试脚本
# 需要先启动Nacos、lobby、gate、game服务

echo "🎮 房间满员自动开始比赛功能测试"
echo "=================================="

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 5

# 1. 用户登录
echo ""
echo "1️⃣ 用户登录"
echo "----------------------------------------"
echo "用户001登录..."
curl -X POST http://localhost:8080/api/game/login \
  -H "Content-Type: application/json" \
  -d '{"userId": "user001", "token": "test_token_001"}'

echo ""
echo "用户002登录..."
curl -X POST http://localhost:8080/api/game/login \
  -H "Content-Type: application/json" \
  -d '{"userId": "user002", "token": "test_token_002"}'

# 2. 创建房间
echo ""
echo ""
echo "2️⃣ 创建房间"
echo "----------------------------------------"
echo "创建2人房间..."
CREATE_RESPONSE=$(curl -s -X POST http://localhost:8080/api/game/rooms \
  -H "Content-Type: application/json" \
  -d '{"roomName": "测试比赛房间", "maxPlayers": 2, "userId": "user001"}')

echo $CREATE_RESPONSE

# 提取房间ID
ROOM_ID=$(echo $CREATE_RESPONSE | grep -o '"roomId":"[^"]*"' | cut -d'"' -f4)
echo "房间ID: $ROOM_ID"

# 3. 第一个用户加入房间
echo ""
echo ""
echo "3️⃣ 第一个用户加入房间"
echo "----------------------------------------"
echo "用户001加入房间..."
curl -X POST http://localhost:8080/api/game/rooms/$ROOM_ID/join \
  -H "Content-Type: application/json" \
  -d '{"userId": "user001"}'

# 4. 第二个用户加入房间（触发满员）
echo ""
echo ""
echo "4️⃣ 第二个用户加入房间（触发满员）"
echo "----------------------------------------"
echo "用户002加入房间（将触发满员自动开始比赛）..."
curl -X POST http://localhost:8080/api/game/rooms/$ROOM_ID/join \
  -H "Content-Type: application/json" \
  -d '{"userId": "user002"}'

# 5. 等待比赛开始
echo ""
echo ""
echo "5️⃣ 等待比赛开始（3秒准备时间）"
echo "----------------------------------------"
echo "⏳ 等待3秒..."
sleep 3

# 6. 检查游戏状态
echo ""
echo ""
echo "6️⃣ 检查游戏状态"
echo "----------------------------------------"
echo "获取游戏状态..."
curl -X GET http://localhost:8080/api/game/status/$ROOM_ID

# 7. 提交游戏动作
echo ""
echo ""
echo "7️⃣ 提交游戏动作"
echo "----------------------------------------"
echo "用户001提交动作..."
curl -X POST http://localhost:8080/api/game/action \
  -H "Content-Type: application/json" \
  -d '{"roomId": "'$ROOM_ID'", "userId": "user001", "action": "MOVE"}'

echo ""
echo "用户002提交动作..."
curl -X POST http://localhost:8080/api/game/action \
  -H "Content-Type: application/json" \
  -d '{"roomId": "'$ROOM_ID'", "userId": "user002", "action": "ATTACK"}'

# 8. 检查房间列表
echo ""
echo ""
echo "8️⃣ 检查房间列表"
echo "----------------------------------------"
echo "获取房间列表..."
curl -X GET "http://localhost:8080/api/game/rooms?page=1&size=10"

echo ""
echo ""
echo "✅ 测试完成！"
echo "=================================="
echo "📋 测试流程总结："
echo "1. 用户登录"
echo "2. 创建2人房间"
echo "3. 第一个用户加入房间"
echo "4. 第二个用户加入房间（触发满员）"
echo "5. 自动开始比赛（3秒准备时间）"
echo "6. 检查游戏状态"
echo "7. 提交游戏动作"
echo "8. 查看房间列表"
echo ""
echo "🔍 查看服务日志以观察完整的自动比赛流程："
echo "- Lobby服务：房间满员检测和Game服务通知"
echo "- Game服务：比赛创建和开始"
echo "- Gate服务：用户通知和消息广播" 